﻿using Microsoft.Extensions.Logging;
using NuGet.Protocol.Core.Types;
using QuickGet.Core.Models;
using QuickGet.Core.Services;

namespace QuickGet.Core
{
    public class SearchPackages : NugetOperationBase
    {
        public SearchPackages(
            ILogger<SearchPackages> logger, 
            SourceCacheContext sourceCache, 
            INugetResourceResolver nugetResourceResolver, 
            INugetSourceRepositoryResolver nugetSourceRepositoryResolver)
            : base(
                  logger, 
                  sourceCache, 
                  nugetResourceResolver, 
                  nugetSourceRepositoryResolver)
        {
        }

        public async Task<List<IPackageSearchMetadata>> GetList(SearchPackagesRequest request, CancellationToken cancellationToken)
        {
            var resource = await _resourceResolver.GetResourceAsync<PackageSearchResource>(request.PackageSourceName, cancellationToken);

            if (resource is null)
            {
                return [];
            }

            var filter = new SearchFilter(request.IncludePreRelease);

            var results = await resource.SearchAsync(
                request.KeyWord,
                filter,
                request.SkipCount,
                request.PageSize,
                _nugetLogger,
                cancellationToken);

            return results.ToList();
        }
    }
}
